package com.hschinese.pronunciation.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.hschinese.pronunciation.R;
import com.hschinese.pronunciation.bean.UserInfo;
import com.hschinese.pronunciation.model.UserInfoModel;
import com.hschinese.pronunciation.utils.Constant;
import com.hschinese.pronunciation.utils.Logger;
import com.hschinese.pronunciation.utils.MD5Utils;
import com.hschinese.pronunciation.utils.SharedPreferenceUtils;
import com.hschinese.pronunciation.utils.UIUtils;
import com.hschinese.pronunciation.utils.UrlUtil;
import com.hschinese.pronunciation.utils.Utils;
import com.hschinese.pronunciation.utils.WebRequestUtil;
import com.hschinese.pronunciation.widget.Header;
import com.hschinese.pronunciation.widget.HsDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private Header mHeader = null;
    private TextView mLogin = null;
    private EditText mEmail, mPassword;
    private TextView mGotoRegister;
    private HsDialog mDialog = null;
    private SharedPreferenceUtils mSharedPrefUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_login);
        initView();
          mSharedPrefUtil = SharedPreferenceUtils.getInstance(LoginActivity.this);
    }

    private void initView() {
        mHeader = (Header)findViewById(R.id.new_login_header);
        mLogin = (TextView)findViewById(R.id.new_login_btn);
        mEmail = (EditText)findViewById(R.id.new_login_email_edit);
        mPassword = (EditText)findViewById(R.id.new_login_pwd_edit);
        mGotoRegister = (TextView)findViewById(R.id.new_login_goto_register);
        mGotoRegister.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG );

        mHeader.setTitle(getResources().getString(R.string.login_title));
        mHeader.setLeftClickListener(this);

        mLogin.setOnClickListener(this);
        mGotoRegister.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void showWaitDialog() {
        mDialog = new HsDialog(LoginActivity.this, R.style.pop_dialog, getResources().getString(R.string.login_dlg_msg), true, false);
        mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                WebRequestUtil.getInstance(LoginActivity.this).cancelByTag(UrlUtil.LOGIN);
            }
        });
        mDialog.show();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.new_login_btn) {
            login();
            showWaitDialog();
        } else if (id == R.id.new_login_goto_register) {
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);
        } else if (id == R.id.id_header_back) {
            this.finish();
        }
    }

    private void login() {
        String email = mEmail.getText().toString();
        String pwd = mPassword.getText().toString();
        Logger.i("email: " + email + " -- pwd: " + pwd);
        if (TextUtils.isEmpty(email)) {
            UIUtils.showToast(LoginActivity.this, getResources().getString(R.string.empty_email), Toast.LENGTH_SHORT);
            return;
        }
//        else if (!Utils.isEmailValid(email)) {
//            UIUtils.showToast(LoginActivity.this, getResources().getString(R.string.wrong_email_format), Toast.LENGTH_SHORT);
//            return;
//        }
        else if (TextUtils.isEmpty(pwd) || !Utils.isPassWordValid(pwd)) {
            UIUtils.showToast(LoginActivity.this, getResources().getString(R.string.empty_pwd), Toast.LENGTH_SHORT);
            return;
        }
        HashMap<String, String> params = new HashMap<String, String>();
        String apkey =  null;
        try {
            apkey = MD5Utils.getMD5(email + Constant.PRODUCT_ID + "hansheng");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if (apkey == null) {
            UIUtils.showToast(LoginActivity.this, "生成apkey失败。", Toast.LENGTH_SHORT);
            return;
        }
        params.put("apkey", apkey);
        params.put("email", email);
        params.put("language", Utils.getLanguage(LoginActivity.this));
        params.put("password", pwd);
        params.put("productID", Constant.PRODUCT_ID);
        WebRequestUtil.getInstance(LoginActivity.this).postRequestString(UrlUtil.LOGIN, params, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject json = new JSONObject(s);
                    boolean b = json.getBoolean("Success");
                    if (b) {
                        Logger.e("xionghy -- login response: " + json.toString());
                        JSONObject js = json.getJSONObject("User");
                        loginSuccess(js);
                    } else {
                        UIUtils.showToast(LoginActivity.this, json.getString("Message"), Toast.LENGTH_SHORT);
                        Logger.e("xionghy -- login response: " + json.getString("Message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    mDialog.dismiss();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Logger.e("xionghy -- login response: " + volleyError.getMessage());
                mDialog.dismiss();
            }
        });
    }

    private void loginSuccess(JSONObject json) {
        try {
            UserInfo userInfo = UserInfoModel.getInstance().getUserInfoObj(json);
            mSharedPrefUtil.setIsLogined(true);
            mSharedPrefUtil.setUserInfo(userInfo);
            Intent it = new Intent(LoginActivity.this, EntryActivity.class);
            it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(it);
            this.finish();
        } catch (JSONException e) {
            Logger.e("xionghy - Login failed. User Data Translate Failed.");
            e.printStackTrace();
        }
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.finish();
    }
}
